package com.qiankun;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Auther: qiankun
 * @Date: 2022/10/24 15:36
 * @Description :
 **/
public class SplitFile {
    private static String SPLIT_TYPE = "l";// 默认按行分割 分割类型，l：为按行分割，s: 为按大小分割 (未支持)
    private static int LINES = 100000; //默认10000行 分割大小 为10000 行
    private static int SIZE = 1024;
    private static String SIZE_TYPE = "MB"; // 支持b、kb、mb
    private static String FILE_PATH = "";
    private static int FILE_COUNT = 1;

    public static void main(String[] args) throws Exception {
        // 获取设置参数
//        if (args.length % 2 != 0) {
//            return;
//        }
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < args.length; i++) {
            if (args[i].equalsIgnoreCase("-t")) {
                SPLIT_TYPE = args[++i];
            }
            if (args[i].equalsIgnoreCase("-l")) {
                LINES = Integer.parseInt(args[++i]);
            }
            if (args[i].equalsIgnoreCase("-s")) {
                SIZE = Integer.parseInt(args[++i]);
                if(SIZE<=0){
                    SIZE = 1;
                }
                SIZE_TYPE = args[++i];
            }
            if (args[i].equalsIgnoreCase("-f")) {
                FILE_PATH = args[++i];
            }
        }
        if (!checkFilePath()) {
            return;
        }
        switch (SPLIT_TYPE) {
            case "l":
                splitFileAccordingToTheNumberOfLines();
                break;
            case "s":
                splitFilesBySize();
                break;
            default:
                System.out.println("不支持类型");
                break;
        }
        System.out.println("共耗时：" + (System.currentTimeMillis() - startTime) + "ms");

    }

    /**
     * 字符串提取 空间大小
     *
     * @return
     */
    private static int strGetSize() {
        int splitSize = 1024 * 1024;// 1MB
        switch (SIZE_TYPE.toUpperCase()) {
            case "K":
                splitSize = SIZE;
                break;
            case "KB":
                splitSize = SIZE * 1024;
                break;
            case "MB":
                splitSize = SIZE * 1024 * 1024;
                break;
        }
        return splitSize;
    }

    /**
     * 检查文件是否存在 路径是否正确
     *
     * @return
     */
    private static boolean checkFilePath() {
        String property = System.getProperty("user.dir");
        if (FILE_PATH == null || FILE_PATH.length() == 0) {
            System.out.println("文件信息有误");
            return false;
        }
        File file = new File(FILE_PATH);
        if (!file.exists()) {
            file = new File(property + "\\" + FILE_PATH);
            if (file.exists()) {
                FILE_PATH = property + "\\" + FILE_PATH;
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 依据大小分割文件
     */
    private static void splitFilesBySize() throws Exception {
        RandomAccessFile file = new RandomAccessFile(FILE_PATH, "r");
        FileChannel channel = file.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(strGetSize());
        int count = 1;
        while (channel.read(buffer) > -1) {
            buffer.flip();
            RandomAccessFile splitFile = new RandomAccessFile(FILE_PATH + "-" + (count++) + ".log", "rw");
            splitFile.getChannel().write(buffer);
            System.out.println("分割文件:" + FILE_PATH + "-" + (count - 1) + ".log");
            buffer.clear();
        }
    }


    /**
     * 根据行数切割文件
     */
    private static void splitFileAccordingToTheNumberOfLines() throws FileNotFoundException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(FILE_PATH)));
        BufferedWriter bufferedWriter = getBufferedWriter();
        int i = 1;
        String line = "";
        try {
            while (((line = bufferedReader.readLine()) != null)) {
                if (i >= LINES) {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                    bufferedWriter = getBufferedWriter();
                    i = 1;
                }
                bufferedWriter.write(line);
                bufferedWriter.write("\n");
                i++;
            }
            System.out.println("分割文件:" + FILE_PATH + "-" + (FILE_COUNT - 1) + ".log");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedReader.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            try {
                bufferedWriter.flush();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            try {
                bufferedWriter.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }


    }

    private static BufferedWriter getBufferedWriter() throws FileNotFoundException {
        return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FILE_PATH + "-" + (FILE_COUNT++) + ".log")));
    }
}
